package lvm

import (
	"bufio"
	"context"
	"fmt"
	"github.com/sirupsen/logrus"
	"strings"
)

// LVList 逻辑分区列表
func LVList(ctx context.Context) (map[string]*LogicalVolume, error) {
	result, err := execCommand(ctx, "lvs",
		"-o", "lv_name,vg_name,lv_size,lv_uuid,lv_path",
		"--noheadings", "--units", "B", "--separator", "||")
	if err != nil {
		return nil, err
	}
	logrus.Debugf("lvlist: %v", result)
	return processLVList(result)
}

// lva||yctc||10737418240B||57xBJM-t3Qx-qkxo-Hha2-pNzL-VNkV-U07VMi
func processLVList(result string) (lvs map[string]*LogicalVolume, err error) {
	scanner := bufio.NewScanner(strings.NewReader(result))
	lvs = make(map[string]*LogicalVolume)
	for scanner.Scan() {
		l := strings.TrimSpace(scanner.Text())
		sps := strings.Split(l, "||")
		if len(sps) < 5 {
			continue
		}
		lv := &LogicalVolume{
			Name:   sps[0],
			VGName: sps[1],
			Size:   parseSize(sps[2]),
			UUID:   sps[3],
			Path:   sps[4],
		}
		lvs[fmt.Sprintf("%s/%s", lv.VGName, lv.Name)] = lv
	}
	if len(lvs) == 0 {
		err = ErrEmpty
	}
	return
}
